//
//  OauthViewController.swift
//  SinaWeiboDemo
//
//  Created by 伍禄林 on 16/9/21.
//  Copyright © 2016年 伍禄林. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class OauthViewController: UIViewController {
    
    let client_id: String = "278327884"
    let redirect_uri: String = "http://www.itcast.com"
    
    let appSecret: String = "e43e956c43582eeaba9f3b4aea4f9119"
    
    let webView = UIWebView()
    
    @objc private func closeBtnClick() {
        
        dismiss(animated: true, completion: nil)
        
    }
    override func loadView() {
        view = webView
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        loadOauthPage()
    }
    
    
    private func loadOauthPage() {
        
        let urlString = "https://api.weibo.com/oauth2/authorize" + "?client_id=" + client_id + "&redirect_uri=" + redirect_uri
        
        let url = NSURL(string: urlString)
        
        let request = NSURLRequest(url: url! as URL)
        
        webView.loadRequest(request as URLRequest)
        
    }
    
    private func setupUI() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(OauthViewController.closeBtnClick))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .plain, target: self, action: #selector(OauthViewController.fullAccount))
        title = "登陆授权"
    }
    
    
    @objc private func fullAccount() {
        
        let jsString = "document.getElementById('userId').value = '13725358161' , document.getElementById('passwd').value = 'Wll~@560';"
        
        webView.stringByEvaluatingJavaScript(from: jsString)
        
    }
}

extension OauthViewController: UIWebViewDelegate {
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        print("webViewDidStartLoad==========")
        SVProgressHUD.show()
        
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        print("webViewDidFinishLoad=======")
        SVProgressHUD.dismiss()
    }
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        print("shouldStartLoadWith=========")
        print(request.url)
        
        guard let urlString = request.url?.absoluteString else {
            return false
        }
        
        
        if urlString.hasPrefix("https://api.weibo.com/") {
            return true
        }
        
        if !urlString.hasPrefix(redirect_uri) {
            return false
        }
        
        print("url========\(request.url)")
        
        guard let query = request.url?.query else {
            return false
        }
        
        let codeStr = "code="
        
        let code = query.substring(from: codeStr.endIndex)
        print("query========\(query)" )
        print("code=======\(code)")
        
        loadAccoseTokent(code: code)
        return false
    }
    
    func loadAccoseTokent(code: String) -> Void {
        
        let AFN = AFHTTPSessionManager();
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let parameters = ["client_id": client_id,"client_secret": appSecret,"grant_type": "authorization_code","code": code, "redirect_uri": redirect_uri]
        /*
         "access_token" = "2.004FX32G07nppS377571b95d6RQ38D";
         "expires_in" = 157679999;
         "remind_in" = 157679999;
            uid = 5812470449;
         */
        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
        AFN.post(urlString, parameters: parameters, progress: nil, success: { (_, result) in
                print(result)
            
            if let dict = result as? [String: AnyObject] {
                
                
                let account = UserAccount(dict: dict)
                
                print("account=======\(account)")
                
                self.getUserInfo(account: account)
//                let access_token = dict["access_token"] as? String
//                let uid = dict["uid"] as? String
//                
//               
//                
//                
//                self.getUserInfo(access_token: access_token!, uid: uid!)
            }
            
            }) { (_, error) in
                print(error)
        }
        
    }
    
    func getUserInfo(account: UserAccount) -> Void {
        
        let urlString = "https://api.weibo.com/2/users/show.json?" + "access_token=" + account.access_token! + "&uid=" + account.uid!
        
        let ANF = AFHTTPSessionManager();
        ANF.get(urlString, parameters: nil, progress: nil, success: { (_, result) in
                print(result)
            if let dict = result as? [String: AnyObject] {
                
                account.avatar_large = dict["avatar_large"] as? String
                account.name = dict["name"] as? String
                
                account.saveAccount()
                print("account========\(account)")
            }
            
            }) { (_, error) in
                print(error)
        }
        
    }
}
